// 封装uni.request api
// const url_all: any = {
// 	'DEV': 'http://192.168.1.167:81', // 开发
// 	'PRO': 'http://121.43.177.20:8181', // 生产
// }
// let BASEURL = url_all['DEV'] // 调整当前环境
import { CONSTANT_URL } from '@/apis/constant'
let BASEURL = CONSTANT_URL
// console.log(BASEURL)
/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @param loading 请求未完成是是否显示加载中，默认为true
*/
export default (path: any, method = 'POST', data = {}, loading = true, showErrToast = true,) => {
	// 获取存储token
	const token = uni.getStorageSync("token");

	if (loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};
	//根据token进行调用函数
	if (token != '') {
		return tokenRequest(path, method, data, loading, showErrToast, token)
	} else {
		return noTokenRequest(path, method, data, loading, showErrToast)
	}
};

// 无token时发送请求函数
function noTokenRequest(path: any, method: any, data: {}, loading: boolean, showErrToast: boolean) {
	return new Promise((resolve, reject) => {
		uni.request({
			// url: BASEURL + path,
			url: path,
			method: method,
			data,
			header: {
                // "X-TENANT-ID": '01K1ACYF8VWKGJ9VQEETJYP6BT'
			},
			success(response: any) {
                if (loading) {
                    uni.hideLoading();
                }
				// console.log('%c响应拦截：', ' background:green', response);
				/* if (response.data.code === 3001) {
					// logout()
				} */
                // console.log(response.data)
				if (response.statusCode !== 200) {
					if (showErrToast) {
					    uni.showToast({
					    	icon: "error",
					        mask: true,
					    	title: '请稍后再试'
					    });
					}
                    reject(response.data);
				} else if (response.data?.code == 50000) {
                    uni.showToast({
                        icon: "error",
                        mask: true,
                        // duration: 4000,
                        title: response.data.msg
                    });
                    uni.removeStorageSync('token')
                    reject(response.data);
                    let pages: any = getCurrentPages()
                    let url1 = pages[pages.length - 1].$page.fullPath
                    let url2 = encodeURIComponent(url1)
                    uni.reLaunch({
                        url: "/pages/login/login?url=" + url1
                    })
                } else {
                    resolve(response.data);
                }
			},
			fail(err) {
                if (loading) {
                    uni.hideLoading();
                }
                console.error(err);
                if (showErrToast) {
                    uni.showToast({
                    	icon: "error",
                        mask: true,
                    	title: '请稍后再试'
                    });
                }
				reject(err);
			},
			complete() {
			}
		});
	});
}


// 有token时发送请求函数
function tokenRequest(path: any, method: any, data: {}, loading: boolean, showErrToast: boolean, token: any) {
	return new Promise((resolve, reject) => {
		uni.request({
			// url: BASEURL + path,
			url: path,
			method: method,
			data,
			header: {
				"Authorization":  token
                // "X-TENANT-ID": '01K1ACYF8VWKGJ9VQEETJYP6BT'
			},
			success(response: any) {
                if (loading) {
                    uni.hideLoading();
                }
				// console.log('%c响应拦截：', ' background:green', response);
				// if (response.data.code === 40101) {
					// logout()
				// }
				// console.log(response.data)
                if (response.statusCode !== 200) {
                	if (showErrToast) {
                	    uni.showToast({
                	    	icon: "error",
                	        mask: true,
                	    	title: '请稍后再试'
                	    });
                	}
                    reject(response.data);
                } else if (response.data?.code == 50000) {
                    uni.showToast({
                        icon: "error",
                        mask: true,
                        // duration: 4000,
                        title: response.data.msg
                    });
                    uni.removeStorageSync('token')
                    reject(response.data);
                    let pages: any = getCurrentPages()
                    let url1 = pages[pages.length - 1].$page.fullPath
                    let url2 = encodeURIComponent(url1)
                    uni.reLaunch({
                        url: "/pages/login/login?url=" + url1
                    })
                } else {
                    resolve(response.data);
                }
			},
			fail(err) {
                if (loading) {
                    uni.hideLoading();
                }
                if (showErrToast) {
                    uni.showToast({
                        icon: "error",
                        mask: true,
                        title: '请稍后再试'
                    });
                }
				console.error(err);
				reject(err);
			},
			complete() {
				// uni.hideLoading();
			}
		});
	});
}

uni.addInterceptor('request', {
    invoke(args) {
        // request 触发前拼接 url 
        // manifest.json配置了h5的跨域，所以h5情况下不能加上BASEURL

        // #ifndef WEB
        args.url = BASEURL.TY + args.url
        // if (args.url.startsWith('/cgi-bin/token') || args.url.startsWith('/wxa/business/getuserphonenumber')) {
        //     args.url = BASEURL.WX + args.url
        // } else {
        //     args.url = BASEURL.TY + args.url
        // }
        // args.url = BASEURL + args.url
        // #endif
    },
    success(args) {
        // 请求成功后，修改code值为1
        // args.data.code = 1
        // uni.hideLoading();
        console.log(args)
        // if (args.data?.code == 50000) {
        // 	uni.showToast({
        // 		icon: "error",
        //         mask: true,
        // 		// duration: 4000,
        // 		title: args.data.msg
        // 	});
            
        //     let pages: any = getCurrentPages()
        //     let url1: any = pages[pages.length - 1].$page.fullPath
        //     console.log(url1)
        //     let url2 = encodeURIComponent(url1)
        //     uni.reLaunch({
        //         url: "/pages/login/login?url=" + url2
        //     })
        //     // uni.reLaunch({
        //     //     url: "/pages/login/login"
        //     // })
        // }
    }, 
    fail(err) {
        // uni.hideLoading();
        console.log('interceptor-fail',err)
    }, 
    complete(res) {
        // console.log('interceptor-complete',res)
    }
})